from users.models import User
from goods.models import GoodsVisitCount
from rest_framework.response import Response
from rest_framework.views import APIView
from datetime import date, timedelta
import datetime
import time
from django.utils import timezone
from meiduo_admin.serializers.statistical import GoodsDayViewSerializer
from rest_framework.permissions import  IsAuthenticated


class TotalView(APIView):
    permission_classes = [IsAuthenticated]
    def get(self, request):
        try:
            count = User.objects.filter(is_staff=False).count()
        except Exception as e:
            print(e)

        today = timezone.now()
        return Response({'count': count, 'date': today})


class UserDayCountView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # 获取凌晨时间
        today = timezone.now()

        # 加入时间大于等于今日

        count = User.objects.filter(is_staff=False, date_joined__gte=today).count()

        return Response({'count': count, 'date': today})


class UserActiveCountView(APIView):
    permission_classes = [IsAuthenticated]
    def get(self, request):
        today = timezone.now()
        count = User.objects.filter(is_staff=False, last_login__gte=today).count()
        return Response({'count': count, 'date': today})


class UserOrderCountView(APIView):
    permission_classes = [IsAuthenticated]
    def get(self, request):
        today = timezone.now()

        # 加入时间大于等于今日

        count = User.objects.filter(is_staff=False, orders__create_time__gte=today).count()

        return Response({'count': count, 'date': today})


class UserMonthCountView(APIView):
    permission_classes = [IsAuthenticated]
    def get(self, request):
        month_list = []

        # 得到每天每天的数据
        today = timezone.now()
        month_start = today - timedelta(days=29)
        for i in range(0, 30):
            day_info = {}
            day_start = month_start + timedelta(days=i)
            day_end = month_start + timedelta(days=i + 1)
            count = User.objects.filter(is_staff=False, date_joined__gte=day_start, date_joined__lt=day_end).count()
            day_info['count'] = count
            day_info['date'] = day_start
            month_list.append(day_info)

        return Response(month_list)


class GoodsDayView(APIView):
    permission_classes = [IsAuthenticated]
    def get(self, request):
        now_date = date.today()
        visit_list = GoodsVisitCount.objects.filter(date__gte=now_date)
        serializer = GoodsDayViewSerializer(visit_list, many=True)
        return Response(serializer.data)
